<template>
  <div class="autumn-container">
    <!-- 面包 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/dashboard' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>个人设置</el-breadcrumb-item>
    </el-breadcrumb>

    <div class="autumn-center">
      <div class="edit-form">
        <el-tabs tab-position="left" style="height: 88%;">
          <el-tab-pane label="基础资料" style="margin-left: 30px;">
            <h2 class="user-title">基础设置</h2>
            <div style="margin-left: 30px;">

              <el-form ref="editFormRef" label-width="90px" :model="editForm" :rules="editFormRules">
                <el-container>
                  <el-main>
                    <el-row>
                      <el-col :span="24">
                        <el-form-item label="姓名" prop="name">
                          <el-input v-model="editForm.name" />
                        </el-form-item>
                      </el-col>
                      <el-col :span="24">
                        <el-form-item label="性别" prop="gender">
                          <el-radio-group v-model="editForm.gender">
                            <el-radio :label="'1'">男</el-radio>
                            <el-radio :label="'2'">女</el-radio>
                          </el-radio-group>
                        </el-form-item>
                      </el-col>
                      <el-col :span="24">
                        <el-form-item label="联系方式" prop="phone">
                          <el-input v-model="editForm.phone" />
                        </el-form-item>
                      </el-col>
                      <el-col :span="24">
                        <el-form-item label="邮箱" prop="email">
                          <el-input v-model="editForm.email" />
                        </el-form-item>
                      </el-col>

                      <el-col :span="24">
                        <el-form-item label="所在地区" prop="areaCode">
                          <autumn-area v-model="selectedArea"></autumn-area>
                        </el-form-item>
                      </el-col>
                      <el-col :span="24">
                        <el-form-item label="常住地址" prop="address">
                          <el-input v-model="editForm.address" />
                        </el-form-item>
                      </el-col>
                    </el-row>

                    <div class="form-foot-button">
                      <el-button type="primary" @click="submit(editFormRef)">保 存</el-button>
                    </div>
                  </el-main>
                  <el-aside style="padding-top: 1%;">
                    <el-form-item prop="avatar">
                      <autumn-avatar v-model="editForm.avatar"></autumn-avatar>
                    </el-form-item>
                  </el-aside>
                </el-container>
              </el-form>

            </div>
          </el-tab-pane>
          <el-tab-pane label="安全设置" style="margin-left: 30px;">
            <h2 class="user-title">安全设置</h2>
            <div>
              <div class="setting-list">
                <div class="item">
                  <div class="content">
                    <div class="title">账户密码</div>
                    <div class="desc">当前密码强度：强</div>
                  </div>
                  <div class="action">
                    <el-link type="primary" :underline="false" @click="showPassword">修改</el-link>
                  </div>
                </div>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <!-- 修改密码弹窗 -->
    <el-dialog v-model="showPwdDialog" width="30%" :close-on-click-modal="false" @close="handleClose">
      <el-form ref="passwordFormRef" label-width="90px" :model="passwordForm" :rules="passwordFormRules">
        <el-row>
          <el-col :span="24">
            <el-form-item label="新密码" prop="password">
              <el-input type="password" v-model="passwordForm.password" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="确认密码" prop="newPassword">
              <el-input type="password" v-model="passwordForm.newPassword" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer" style="text-align: right;">
          <el-button type="primary" @click="updatePassword(passwordFormRef)">保&nbsp;&nbsp;存</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script lang="ts">
export default { name: 'UserProfile' }
</script>

<script setup lang="ts">
import { reactive, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, FormInstance } from 'element-plus'
import GlobalStore from 'src/store/global'
import { remove } from 'src/util/auth'
import { logout } from 'src/api/home'
import { viewCurrent, updateCurrent, updateCurrentPassword } from 'src/api/system/account'

const editFormRef = ref<FormInstance>()
const passwordFormRef = ref<FormInstance>()
const avatarRef = ref()

const store = GlobalStore()
const router = useRouter()

// 定义变量
const selectedArea = ref('')
const avatarUrl = ref('')
const editForm = reactive({
  name: '',
  avatar: '',
  gender: '',
  email: '',
  phone: '',
  areaCode: '',
  address: ''
})

// 查询当前用户
viewCurrent().then(({ data }) => {
  Object.assign(editForm, data)
  if (data.areaCode) {
    selectedArea.value = data.areaCode
  }
})

watch(selectedArea, (newVal: any, oldVal) => {
  if (!newVal || newVal.length === 0) {
    editForm.areaCode = ''
  } else {
    editForm.areaCode = newVal instanceof Array ? newVal[newVal.length - 1] : newVal
  }
})

// 修改当前用户信息
const editFormRules = {
  userName: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ]
}

const submit = function (formEl: FormInstance | undefined) {
  if (!formEl) return
  formEl.validate((valid: boolean) => {
    if (!valid) return
    updateCurrent(editForm)
  })
}

// 修改密码
const showPwdDialog = ref(false)
const passwordForm = reactive({
  password: '',
  newPassword: ''
})
const handleClose = function () {
  if (!passwordFormRef.value) return
  passwordFormRef.value.resetFields()
}
const validatePass = (rule: any, value: string, callback: Function) => {
  if (!value) {
    callback(new Error('请再次输入密码'))
  } else if (value !== passwordForm.password) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}
const passwordFormRules = {
  password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { pattern: /^(?![a-zA-Z]+$)(?![0-9]+$)(?![._~!@#$^&*]+$)(?![0-9a-zA-Z]+$)(?![0-9._~!@#$^&*]+$)(?![a-zA-Z._~!@#$^&*]+$)[A-Za-z0-9._~!@#$^&*]{8,20}$/, message: '长度在 8 到 20 个字符，并包含数字、大小字母、特殊符号中的三个', trigger: ['change', 'blur'] }
  ],
  newPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: validatePass, trigger: ['change', 'blur'] }
  ]
}
const showPassword = function () {
  showPwdDialog.value = true
}
const updatePassword = function (formEl: FormInstance | undefined) {
  if (!formEl) return
  formEl.validate((valid: boolean) => {
    if (!valid) return
    updateCurrentPassword(passwordForm).then(data => {
      showPwdDialog.value = false
      logout().then(data => {
        cancel()
      }).catch(() => {
        cancel()
      })
    })
  })
}

// 重置
const cancel = function () {
  remove()
  sessionStorage.removeItem('activeMenu')
  store.$reset()
  router.replace('/login')
}
</script>

<style lang="scss" scoped>
.user-title {
  margin: 0;
  margin-bottom: 30px;
  font-weight: 400;
}

.avatar-uploader .el-upload {
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  border: 1px dashed #cccccc;
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}

.avatar {
  width: 150px;
  height: 150px;
  display: block;
}

.setting-list {
  .item {
    display: flex;
    padding: 10px 0;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #e8e8e8;

    .content {
      .title {
        margin-bottom: 5px;
        color: #666;
      }

      .desc {
        font-size: 14px;
        color: #999;
      }
    }
  }
}
</style>
